package org.yaac.server.egql.evaluator.aggregator;

import java.math.BigDecimal;
import java.util.Date;

import org.yaac.server.egql.evaluator.EvaluationResult;

public class SumAggregator implements Aggregator {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private BigDecimal sum;
	
	/**
	 * 
	 */
	public SumAggregator() {
		sum = BigDecimal.ZERO;
	}

	@Override
	public void aggregate(EvaluationResult delta) {
		if (delta.getPayload() == null) {
			return;
		}
		
		if (delta.getPayload() instanceof Boolean) {
			Boolean val = (Boolean) delta.getPayload();
			if (val) {	// plus one when true
				sum = sum.add(BigDecimal.ONE);
			}
		} else if (delta.getPayload() instanceof BigDecimal) {
			sum = sum.add((BigDecimal) delta.getPayload());
		} else if (delta.getPayload() instanceof Date) {
			// always add one
			sum = sum.add(BigDecimal.ONE);
		}
	}

	@Override
	public String asString() {
		return sum.toPlainString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((sum == null) ? 0 : sum.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SumAggregator other = (SumAggregator) obj;
		if (sum == null) {
			if (other.sum != null)
				return false;
		} else if (!sum.equals(other.sum))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "SumAggregator [sum=" + sum + "]";
	}

	@Override
	public BigDecimal getResult() {
		return sum;
	}
}
